<?php

include_once('Logging.php');
class JRDExpressClass
{
    const URL_TEST = 'http://ptopen.jinridapaotui.com/open.php/api/';  # 地址【测试环境】
//    const SIGN_TEST = '6644f9d7c5e01eec770f691fd96c50bf';  # 签名【测试环境】
    const SIGN_TEST = '6d552e3bce87197e38b571640108eb71';  # 签名【测试环境】 20201228 新

    const URL = 'http://ptopen.jinridapaotui.com/open.php/api/';         # 地址【正式环境】
    const SIGN = '6644f9d7c5e01eec770f691fd96c50bf';  # 签名【正式环境】

    private $isDebug = true;
    private $sign = true;
    public function __construct($isDebug,$sign)
    {
        $this->isDebug = $isDebug;
        $this->sign = $sign;
    }

    /**
     * 下单
     * @param $parameter
     * 主 经纬度
     */
    public function push_order($data){
        $sign =  $this->sign;
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'createorder?sign='.$sign;
        $tmpt = strtotime(date('Y-m-d H:i:s',strtotime('+2 hour')));
        $pickupTime = $this->isDebug ? $tmpt : strtotime($data['shop_delivery_time']);
        $jrd_type = $data['jrd_type'] == 2 ? $data['jrd_type'] : 1;
        $parameters['start_time'] =    $pickupTime;                  # 预约配送时间
        $parameters['driver_type'] = $jrd_type;                      # 预约骑手类型（1=机动车 2=电动车）
        $parameters['goods_name'] = $data['products'][0]['product_name']; # 物品名称
        $parameters['weight'] = $data['actual_weight'];              # 物品重量（单位：kg）
        $parameters['message'] = $data['shop_express_remark'];       # 备货信息

        if($this->isDebug){
            $parameters['start_lat'] = 23.106414;
            $parameters['start_lng'] = 113.324553;
            $parameters['start_address'] = '广东省 广州市 广州塔';

            $parameters['target_address'] = '广东省 广州市 腾讯微信总部';
            $parameters['target_lng'] =  113.32456;
            $parameters['target_lat'] = 23.1001;
        }else{
            $parameters['start_lat'] = $data['deliver_lat'];             # 取货地址纬度
            $parameters['start_lng'] = $data['deliver_lng'];             # 取货地址经度
            $parameters['start_address'] = $data['deliver_province'].$data['deliver_city'].$data['deliver_area'].$data['deliver_address'];             # 取货地址

            if($data['slat'] && $data['slng']){
                $parameters['target_lng'] = $data['slng'];
                $parameters['target_lat'] = $data['slat'];
            }else{
                $parameters['target_lng'] = $data['lng'];
                $parameters['target_lat'] = $data['lat'];
            }
            $parameters['target_address'] = $data['receiver_address'];   # 收货地址

        }

        $parameters['target_name'] = $data['receiver'];              # 收货人名称
        $parameters['target_phone'] = $data['receiver_tel'];         # 收货人联系手机号码
        $parameters['start_name'] = $data['shop_name'];              # 取货人名称
        $parameters['start_phone'] = $data['deliver_phone'];         # 取货人联系手机号码 发货
        $parameters['partner_order_no'] = $data['shop_express_no'];  # 第三方订单号码（宅配订单号）
        $result =$this->http_post($url, json_encode($parameters,JSON_UNESCAPED_UNICODE), '','json', '','');
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }


    /**
     * 添加小费
     */
    public function addTip($order_no,$tips){
        $sign =  $this->sign;

        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'tiporder?sign='.$sign;
        $parameter = [];
        $parameter['order_no'] = $order_no;
        $parameter['tip'] = $tips;
        $result =$this->http_post($url, json_encode($parameter,JSON_UNESCAPED_UNICODE), '','json', '','');
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }

    /**
     * 取消订单
     * @param $parameter
     */
    public function formalCancel($parameter){
        $sign =  $this->sign;
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'cancelorder?sign='.$sign;
        $result =$this->http_post($url, json_encode($parameter,JSON_UNESCAPED_UNICODE), '','json', '','');
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }

    /**
     * 骑手位置
     * @param $parameter
     */
    public function orderrider($order_no){
        $sign =  $this->sign;
        $parameter['order_no'] = $order_no;
        $url = (($this->isDebug) ? self::URL_TEST : self::URL).'orderrider?sign='.$sign;
        $result =$this->http_post($url, json_encode($parameter,JSON_UNESCAPED_UNICODE), '','json', '','');
        if (!empty($result)){
            $result=json_decode($result, true);
        }
        return $result;
    }


    private function http_post($url, $param, $post_file = false, $contenttype = '', $msg = '')
    {
        $log = new Logging();
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (empty($contenttype)) {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded; charset=utf-8'));
        } else if ($contenttype == "json") {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));

        }

        $strPOST='';
        if (is_string($param)) {
            $strPOST = $param;
        } else {
            $aGET = array();
            foreach ($param as $key => $val) {
                $aGET[] = $key . "=" . ($val);
            }
            $strPOST = join("&", $aGET);
        }

//        //$strPOST=http_build_query($param, '', '&');
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 60);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

        $time=strtotime(date('Y-m-d H:i:s'));
        $log->lfile('jrd_express');
        $log->lwrite($time.','.($url));
        if (!empty($msg))$log->lwrite($time.','.$msg);
        $log->lwrite($time.','.$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);

        $log->lwrite($time.','.(json_encode(json_decode($sContent,true),JSON_UNESCAPED_UNICODE)));

        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }


}

?>